﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace NCMIS.ServiceModel
{
    /// <summary>
    /// Represents a <see cref="WebHttpBehavior"/> that does not display friendly error messages.
    /// </summary>
    public class FaultingWebHttpBehavior : WebHttpBehavior
    {
        protected override void AddServerErrorHandlers(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            endpointDispatcher.ChannelDispatcher.ErrorHandlers.Clear();
            endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(new ErrorHandler());
        }

        /// <summary>
        /// Represents a custom error handler.
        /// </summary>
        public class ErrorHandler : IErrorHandler
        {
            public bool HandleError(Exception error)
            {
                return true;
            }

            public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
            {
                FaultCode faultCode = FaultCode.CreateSenderFaultCode(error.GetType().Name, "http://cmis.episerver.com/exceptions");
                fault = Message.CreateMessage(version, faultCode, error.Message, null);
            }
        }
    }
}
